<?php

namespace App\Http\Controllers\Operation;

use App\Classes\Publish\Publication;
use App\Http\Controllers\Controller;
use App\Http\Requests\Operation\ContentTemplateDetailsRequest;
use App\Jobs\Publish\ContentTemplateJob;
use App\Models\Operation\ContentTemplate;
use App\Models\Operation\ContentTemplateDetails;
use App\Models\Operation\ContentTemplateType;
use App\Models\Operation\TemplateAreaData;
use App\Models\Operation\TemplateSubcolumnVassetiData;
use App\Models\Publish\PublishContentTemplateHistory;
use App\Repositories\Operation\ContentTemplateDetailsRepository;
use DB;
use Encore\Admin\Controllers\ModelForm;
use Encore\Admin\Facades\Admin;
use Encore\Admin\Form;
use Encore\Admin\Grid;
use Encore\Admin\Layout\Content;
use Flash;
use Illuminate\Http\Request;
use Illuminate\Support\Facades\Input;
use Illuminate\Support\Facades\Route;
use Response;

class ContentTemplateDetailsController extends Controller
{
    use ModelForm;

    private $contentTemplateDetailsRepository;

    public function __construct(ContentTemplateDetailsRepository $contentTemplateDetailsRepo)
    {
        $this->contentTemplateDetailsRepository = $contentTemplateDetailsRepo;
    }

    /**
     * Display a listing of the resource.
     *
     * @return \Illuminate\Http\Response
     */
    public function index(Request $request)
    {
        return Admin::content(function (Content $content) use ($request) {
            $content->header(__('operation.content_template_details.index_header'));
            $content->description(__('operation.content_template_details.index_description'));

            $content->body($this->grid($request));
        });
    }

    /**
     * Show the form for creating a new resource.
     *
     * @return \Illuminate\Http\Response
     */
    public function create()
    {
        return Admin::content(function (Content $content) {

            $content->header(__('operation.content_template_details.create_header'));
            $content->description(__('operation.content_template_details.create_description'));

            $content->body($this->form());

        });
    }

    /**
     * Store a newly created resource in storage.
     *
     * @param  \Illuminate\Http\Request  $request
     * @return \Illuminate\Http\Response
     */
    public function store(ContentTemplateDetailsRequest $request)
    {
        $input                  = $request->all();
        $contentTemplateDetails = $this->contentTemplateDetailsRepository->create($input);

        Flash::success(__('operation.content_template_details.saved_success'));
        // dd($request->content_template_id);
        return Input::get('_previous_') ? redirect(Input::get('_previous_')) : redirect(route('operation.content_template_details.index', ['content_template_id' => $request->content_template_id]));
    }

    /**
     * Display the specified resource.
     *
     * @param  int  $id
     * @return \Illuminate\Http\Response
     */
    public function show($id)
    {
        $contentTemplateDetails = $this->contentTemplateDetailsRepository->findWithoutFail($id);

        if (empty($ContentTemplateDetails)) {
            Flash::error(__('operation.content_template_details.not_found'));

            return redirect(route('operation.content_template_details.index'));
        }

        return view('operation.content_template_details.show')->with('contentTemplateDetails', $contentTemplateDetails);
    }

    /**
     * Show the form for editing the specified resource.
     *
     * @param  int  $id
     * @return \Illuminate\Http\Response
     */
    public function edit($id)
    {
        return Admin::content(function (Content $content) use ($id) {

            $content->header(__('operation.content_template_details.edit_header'));
            $content->description(__('operation.content_template_details.edit_description'));

            $content->body($this->form()->edit($id));
        });
    }

    /**
     * Update the specified resource in storage.
     *
     * @param  \Illuminate\Http\Request  $request
     * @param  int  $id
     * @return \Illuminate\Http\Response
     */
    public function update(ContentTemplateDetailsRequest $request, $id)
    {
        $contentTemplateDetails = $this->contentTemplateDetailsRepository->findWithoutFail($id);

        if (empty($contentTemplateDetails)) {
            Flash::error(__('operation.content_template_details.not_found'));

            return redirect(route('operation.content_template_details.index'));
        }

        $input = $request->all();

        $contentTemplateDetails = $this->contentTemplateDetailsRepository->update($input, $id);

        Flash::success(__('operation.content_template_details.updated_success'));

        return Input::get('_previous_') ? redirect(Input::get('_previous_')) : redirect(route('operation.content_template_details.index'));
    }

    /**
     * Remove the specified resource from storage.
     *
     * @param  int  $id
     * @return \Illuminate\Http\Response
     */
    public function destroy($id)
    {
        // 根据 `,` 判断传递过来的是单个id还是多个id
        if (substr_count($id, ',') >= 1) {
            $id = explode(",", $id);
        }

        // 如果是数组则进行批量删除
        if (is_array($id)) {
            if ($flag = $this->contentTemplateDetailsRepository->batchDelete('id', $id)) {
                return response()->json(['message' => __('operation.content_template_details.deleted_success'), 'status' => $flag]);
            } else {
                return response()->json(['message' => __('base.deleted.error'), 'status' => $flag]);
            }
        }

        $contentTemplateDetails = $this->contentTemplateDetailsRepository->findWithoutFail($id);

        if (empty($contentTemplateDetails)) {
            Flash::error(__('operation.content_template_details.not_found'));

            return redirect(route('operation.content_template_details.index'));
        }

        if ($flag = $this->contentTemplateDetailsRepository->delete($id)) {
            return response()->json(['message' => __('operation.content_template_details.deleted_success'), 'status' => $flag]);
        } else {
            return response()->json(['message' => __('base.deleted.error'), 'status' => $flag]);
        }
    }

    // 判断是否已有上线发布的内容的模板
    public function isPublished(Request $request)
    {
        // 发布功能
        if (Admin::user()->cannot('operation.content_template_details.down')) {
            return response()->json(['status' => 'error', 'content' => '您的权限不够!']);
        }
        $templateDetailsId = $request->id;
        // 判断此模板是否上线
        $templateDetails = ContentTemplateDetails::with(['contentTemplate', 'contentTemplate.contentTemplateType'])->where(['id' => $templateDetailsId])->first();

        if ($templateDetails->online_status != 1) {
            return response()->json(['status' => 'error', 'content' => '该资源未上线!']);
        }
        $template_no   = $templateDetails->contentTemplate->template_no;
        $template_type = strtolower($templateDetails->contentTemplate->contentTemplateType->name);
        // 此内容模板是否有内容
        $count = TemplateAreaData::where(['template_type' => $template_type, 'template_no' => $template_no, 'template_details_id' => $templateDetails->id])->count();
        if (!$count) {
            return response()->json(['status' => 'error', 'content' => '此内容模板没有添加内容!']);
        }

        // 相同模板,判断是否已有上线发布的内容模板
        $isPublished = ContentTemplateDetails::onlineStatus()->onlinePublished()->where(['content_template_id' => $templateDetails->content_template_id])->first();

        if ($isPublished) {
            return response()->json(['status' => 'published', 'content' => $templateDetailsId]);
        }
        return response()->json(['status' => 'success', 'content' => $templateDetailsId]);
    }

    /**
     * 发布功能
     */
    public function publish(Request $request)
    {
        $template_details_id = (int) $request->id;
        // 发布功能
        if (Admin::user()->cannot('operation.content_template_details.down')) {
            return response()->json(['status' => 'error', 'content' => '您的权限不够!']);
        }
        $templateDetailsId = $request->id;
        // 判断此模板是否上线
        $templateDetails = ContentTemplateDetails::with(['contentTemplate', 'contentTemplate.contentTemplateType'])->where(['id' => $templateDetailsId])->first();

        if ($templateDetails->online_status != 1) {
            return response()->json(['status' => 'error', 'content' => '该资源未上线!']);
        }
        $template_no = $templateDetails->contentTemplate->template_no;
        // $template_type = strtolower($templateDetails->contentTemplate->contentTemplateType->name);
        $template_type = strtolower('AREA');
        // 此内容模板是否有内容
        $count = TemplateAreaData::where(['template_type' => $template_type, 'template_no' => $template_no, 'template_details_id' => $templateDetails->id])->count();
        if (!$count) {
            return response()->json(['status' => 'error', 'content' => '此内容模板没有添加内容!']);
        }
        $content_template_id = $templateDetails->content_template_id;
        /**
         * 区位模板005发布数据量大放入队列执行
         */
        if ($request->action === 'publishMany') {
            $publishContentTemplateHistory                 = new PublishContentTemplateHistory;
            $publishContentTemplateHistory->batch_no       = date('YmdHis');
            $publishContentTemplateHistory->task_no        = date('YmdHis') . uniqid();
            $publishContentTemplateHistory->done_count     = 0;
            $publishContentTemplateHistory->success_count  = 0;
            $publishContentTemplateHistory->error_count    = 0;
            $publishContentTemplateHistory->count          = $count;
            $publishContentTemplateHistory->content        = "开始";
            $publishContentTemplateHistory->consuming_time = 0;
            $publishContentTemplateHistory->used_memory    = 0;
            $publishContentTemplateHistory->template_type  = 0;
            $publishContentTemplateHistory->template_type  = $template_type;
            $publishContentTemplateHistory->template_no    = $template_no;
            $publishContentTemplateHistory->user_id        = Admin::user()->id;
            $publishContentTemplateHistory->save();
            // 触发队列
            (new ContentTemplateJob($publishContentTemplateHistory, $template_type, $template_no, $template_details_id, $content_template_id))->handle();
            //  dispatch(new ContentTemplateJob($publishContentTemplateHistory, $template_type, $template_no, $template_details_id, $content_template_id));
            return response()->json(['status' => 'success', 'content' => $publishContentTemplateHistory->task_no]);
        } else {
            // 准备数据
            $datas    = $this->getTemplateAreaData($template_type, $template_no, $template_details_id);
            $imgDatas = self::getTemplateAreaImg($template_type, $template_no, $template_details_id);

            // 删除区位模板数据
            self::deleteTemplateAreaData($template_type, $template_no);
            self::deleteTemplateAreaImg($template_type, $template_no);
            self::updatePublishStatus($content_template_id, $template_details_id);
            $result1 = DB::connection('interface')->table('template_area_datas')->insert($datas);
            $result2 = DB::connection('interface')->table('template_area_images')->insert($imgDatas);
            /**
             * 2017-11-21 18:37 add delete 上线发布删除缓存中的内容
             */
            $templateKey = 'template:area:';
            // 调用瀚动接口清除缓存的路由'
            $requestData = [
                'redis_key' => $templateKey . $template_no,
            ];
            // 请求类型
            $type = "post";
            $url  = config('custom.base.cache_host') . "clear_cache"; // http://10.69.42.146/
            // $url        = "http://10.69.42.146/clear_cache?" . http_build_query($requestData);
            $interfaceResult = proxy_http_request($type, $url, $requestData);

            return response()->json(['status' => 'success', 'content' => $result1 && $result2 ? '上线操作成功!' : '上线操作失败']);
        }

    }

    public function grid(Request $request)
    {
        return Admin::grid(ContentTemplateDetails::class, function (Grid $grid) use ($request) {
            $grid->model()->where('content_template_id', $request->content_template_id);
            // 添加按钮
            // if (Admin::user()->can('operation.content_template_details.create')) {
            // $grid->disableCreation();
            // }

            // 编辑和删除按钮
            $grid->actions(function ($actions) {
                $id                  = $actions->getKey();
                $publish_down_status = $actions->row->publish_down_status;
                $online_status       = $actions->row->online_status;
                $publish_status      = $actions->row->publish_status;
                $content_template_id = $actions->row->content_template_id;
                if ($templateTypeName = ContentTemplateType::where(['id' => $actions->row->content_template['content_template_type_id']])->first()->value('name')) {
                    $templateType = $templateTypeName;
                } else {
                    $templateType = "AREA";
                }
                $templateNo = $actions->row->content_template['template_no'] ? $actions->row->content_template['template_no'] : "001";
                $actions->prepend('<a href="' . route('operation.content_templates.data_create', ['template_type' => $templateType, 'template_no' => $templateNo, 'templateDetailsId' => $id, 'online_status' => $online_status, 'content_template_id' => $content_template_id]) . '"><i class="fa fa-list"></i></a>');

                // 上线按钮
                if ($publish_down_status === 1 && $online_status === 0 && Admin::user()->can('operation.content_template_details.up')) {
                    $url      = route('operation.content_template_details.up');
                    $function = "upAndDownByOne('$url', 'post', {id: $id,action: 'up',_token: LA.token})";
                    $actions->append('<a href="javascript:void(0)" onclick="' . $function . '" title="上线"><i class="fa fa-arrow-up"></i></a>');
                }
                // 下线按钮
                if ($online_status === 1 && Admin::user()->can('operation.content_template_details.down')) {
                    $url      = route('operation.content_template_details.down');
                    $function = "upAndDownByOne('$url', 'post', {id: $id,action: 'down',_token: LA.token})";
                    $actions->append('<a href="javascript:void(0)" onclick="' . $function . '" title="下线"><i class="fa fa-arrow-down"></i></a>');
                }

                // 上线发布按钮
                // if ($online_status === 1 && $publish_status === 0 && Admin::user()->can('operation.content_template_details.publish_one')) {
                //     // $url      = route('operation.content_template_details.publish_one');
                //     $url      = route('operation.content_template_details.is_published');
                //     $function = "publishContentTemplate('$url', 'post', {id: $id,action: 'publish',_token: LA.token})";
                //     $actions->append('<a href="javascript:void(0)" onclick="' . $function . '" title="上线发布"><i class="fa fa-cloud-upload"></i></a>');
                // }
                if ($online_status === 1 && $publish_status === 0 && Admin::user()->can('operation.content_template_details.publish_one')) {
                    // 如果是区位模板005的话需要走队列
                    if ($templateType == 'AREA' && $templateNo == '005') {
                        $url      = route('operation.content_template_details.publish_one');
                        $function = "publishMany('$url', 'post', {id: $id,action: 'publishMany',_token: LA.token})";
                    } else {
                        $url = route('operation.content_template_details.publish_one');
                        // $url      = route('operation.content_template_details.is_published');
                        $function = "publishOne('$url', 'post', {id: $id,action: 'publishOne',_token: LA.token})";
                    }
                    $actions->append('<a href="javascript:void(0)" onclick="' . $function . '" title="上线发布"><i class="fa fa-cloud-upload"></i></a>');
                }
                // 下线发布按钮
                if ($online_status === 0 && $publish_down_status === 0 && Admin::user()->can('operation.content_template_details.publish_down_one')) {
                    $url      = route('operation.content_template_details.publish_down_one');
                    $function = "upAndDownByOne('$url', 'post', {id: $id,action: 'publishDown',_token: LA.token})";
                    $actions->append('<a href="javascript:void(0)" onclick="' . $function . '" title="下线发布"><i class="fa fa-cloud-download"></i></a>');
                }

                // 编辑按钮
                if (Admin::user()->cannot('operation.content_template_details.edit')) {
                    $actions->disableEdit();
                }
                // 删除按钮
                if (Admin::user()->cannot('operation.content_template_details.destroy')) {
                    $actions->disableDelete();
                }
                // 只有状态下线的资源才可以编辑, 删除
                if ($publish_down_status === 0) {
                    $actions->disableEdit();
                    $actions->disableDelete();
                }
            });

            //添加按钮
            if (Admin::user()->cannot('operation.content_template_details.create')) {
                $grid->disableCreation();
            }
            // 编辑按钮
            // if (Admin::user()->can('operation.content_template_details.edit')) {
            //     $actions->disableEdit();
            // }
            // // 删除按钮
            // if (Admin::user()->can('operation.content_template_details.destroy')) {
            //     $actions->disableDelete();
            // }

            // //导出按钮
            // if (!\Gate::check('operation.content_template_details.export')) {
            //     $grid->disableExport();
            // }

            // //批量操作
            $grid->tools(function ($tools) use ($request) {
                // 去掉跳转列表按钮
                // $tools->batch(function ($batch) {
                //     // 批量删除按钮
                //     if (!\Gate::check('operation.content_template_details.batch_destroy')) {
                //         $batch->disableDelete();
                //     }
                // });

                // 2017-11-22 add 清除缓存按钮
                if (Admin::user()->can('operation.content_template_details.clear_cache')) {
                    $tools->append('<a href=' . route('operation.content_template_details.clear_cache', ['content_template_id' => $request->content_template_id]) . ' class="btn btn-sm btn-warning pull-right" style="margin-right: 10px"><i class="fa fa-ban"></i> 清除缓存</a>');
                }
                $tools->append('<a href="javascript:void(0)" onclick="history.go(-1)" class="btn btn-default btn-sm" style="margin-right: 0px"> <i class="fa fa-arrow-left"></i>返回</a>');
            });

            $grid->column('contentTemplate.name', '所属内容模板')->sortable();
            $grid->column('id', 'ID')->sortable();
            $grid->column('name', '名称')->sortable();
            $grid->column('title', '标题')->sortable();
            $grid->column('subtitle', '副标题')->sortable();
            $grid->column('start_at', '开始时间')->sortable();
            $grid->column('end_at', '结束时间')->sortable();
            $grid->column('short_desc', '简介');
            $grid->column('created_at', '创建时间')->sortable();
            $grid->column('updated_at', '更新时间')->sortable();

            $grid->column('online_status', '上线状态')->display(function ($val) {
                switch ($val) {
                    case 0:
                        return '<span class="badge bg-red">下线</span>';
                        break;
                    case 1:
                        return '<span class="badge bg-green">上线</span>';
                        break;
                    default:
                        return '未知';
                }
            })->sortable();

            $grid->column('publish_status', '发布状态')->display(function ($val) {
                switch ($this->online_status) {
                    case 0:
                        switch ($this->publish_down_status) {
                            case 0:
                                return '<span class="badge bg-red">下线未发布</span>';
                                break;
                            case 1:
                                return '<span class="badge bg-green">下线已发布</span>';
                                break;
                            default:
                                return '未知';
                        }
                        break;
                    case 1:
                        switch ($this->publish_status) {
                            case 0:
                                return '<span class="badge bg-red">上线未发布</span>';
                                break;
                            case 1:
                                return '<span class="badge bg-green">上线已发布</span>';
                                break;
                            default:
                                return '未知';
                        }
                        break;
                    default:
                        return '未知';
                }
            })->sortable();

            /**
             * 过滤处理
             */
            $grid->filter(function ($filter) {
                // 禁用id查询框
                $filter->disableIdFilter();
                // 模板别名
                $filter->like('title', '内容模板标题');
                $filter->like('id', 'ID');
            });
        });
    }

    /**
     * 区位模板进度条
     */
    public function publishProgress(Request $request)
    {
        $taskNo = $request->input('task_no');
        $data   = PublishContentTemplateHistory::where('task_no', $taskNo)->first();
        if ($data) {
            // 记录数为0[异常]
            if ($data->count === 0) {
                return response()->json(['content' => '记录数为0!', 'status' => 'success']);
            }
            // 完成数为0
            if ($data->done_count === 0) {
                return response()->json(['content' => '0%', 'status' => 'progress']);
            }
            // 完成的时候
            if ($data->count === $data->done_count) {
                return response()->json(['content' => $data->content, 'status' => 'success']);
            }
            // 异常
            if ($data->count < $data->done_count) {
                return response()->json(['content' => '任务异常, 完成数大于总数！', 'status' => 'success']);
            }
            return response()->json(['content' => ceil($data->done_count * 100 / $data->count) . '%', 'status' => 'progress']);
        } else {
            return response()->json(['content' => "非法任务号, 找不到该任务号的任务!", 'status' => 'success']);
        }
    }
    /**
     * 单个上下线功能,单个,单个下线发布功能
     */
    public function batchModerate(Request $request)
    {
        $user_id = Admin::user()->id;
        switch ($request->action) {
            // 上线
            case 'up':
                if (Admin::user()->cannot('operation.content_template_details.up')) {
                    return response()->json(['status' => 'error', 'content' => '您的权限不够!']);
                }
                // 先判断是否已有上线内容
                $contentTemplateDetails = ContentTemplateDetails::where('id', $request->id)->first();
                if ($contentTemplateDetails->online_status === 1) {
                    return response()->json(['status' => 'error', 'content' => '该资源已上线!']);
                }

                $result = Publication::updateOne(new ContentTemplateDetails(), $request->id, [
                    'online_status'       => 1,
                    'publish_down_status' => 0,
                    'user_id'             => $user_id,
                    'online_at'           => date('Y-m-d H:i:s'),
                ]);
                return response()->json(['status' => 'success', 'content' => $result ? '上线操作成功!' : '上线操作失败']);
            // 下线
            case 'down':
                if (Admin::user()->cannot('operation.content_template_details.down')) {
                    return response()->json(['status' => 'error', 'content' => '您的权限不够!']);
                }
                $result = Publication::updateOne(new ContentTemplateDetails(), $request->id, [
                    'online_status'  => 0,
                    'publish_status' => 0,
                    'user_id'        => $user_id,
                    'offline_at'     => date('Y-m-d H:i:s'),
                ]);
                return response()->json(['status' => 'success', 'content' => $result ? '下线操作成功!' : '下线操作失败']);
            // 下线发布
            case 'publishDown':
                if (Admin::user()->cannot('operation.content_template_details.publish_one')) {
                    return response()->json(['status' => 'error', 'content' => '您的权限不够!']);
                }
                // 找出此模板详情对应的区位模板
                $templateDetails = ContentTemplateDetails::with(['contentTemplate', 'contentTemplate.contentTemplateType'])->where('id', $request->id)->first();
                // ['online_status' => 0, 'publish_down_status' => 0]
                if ($templateDetails->online_status !== 0) {
                    return response()->json(['status' => 'error', 'content' => '该资源未下线!']);
                }
                if ($templateDetails->publish_status !== 0) {
                    return response()->json(['status' => 'error', 'content' => '该资源未发布!']);
                }
                if ($templateDetails->publish_down_status === 1) {
                    return response()->json(['status' => 'error', 'content' => '该资源已下线发布!']);
                }
                $template_type       = strtolower($templateDetails->contentTemplate->contentTemplateType->name);
                $template_no         = $templateDetails->contentTemplate->template_no;
                $content_template_id = $templateDetails->content_template_id;
                $result1             = true;
                // 查询一下相同模板是否有其他已上线并发布的模板,有的话,咋不删除接口库内容
                if (!ContentTemplateDetails::onlineStatus()->onlinePublished()->where('content_template_id', $content_template_id)->where('id', '<>', $request->id)->first()) {
                    // 删除接口库中对应的数据
                    $result1 = self::deleteApi($template_type, $template_no);
                }
                // 更新状态
                $templateDetails->publish_down_status = 1;
                $templateDetails->user_id             = $user_id;
                $result2                              = $templateDetails->save();

                $content = $result1 && $result2 ? '下线发布成功' : '下线发布失败';
                return response()->json(['status' => 'success', 'content' => $content]);
        }
    }

    public function form()
    {
        return Admin::form(ContentTemplateDetails::class, function (Form $form) {
            // ID
            $form->display('id', 'ID');
            // 模板类型
            $contentTemplates = ContentTemplate::orderBy('listorder', 'asc')->pluck('name', 'id')->toArray();
            $form->select('content_template_id', '所属内容模板')->options(["" => "无"] + $contentTemplates);
            $form->text('name', '名称');
            $form->text('title', '标题');
            $form->text('subtitle', '副标题');
            $form->datetimeRange('start_at', 'end_at', '有效期')->default(['start' => date('Y-m-d H:i:s', time()), 'end' => date('Y-m-d H:i:s', time())]);
            $form->textarea('short_desc', '简介');

            $form->display('created_at', __('base.created_at'));
            $form->display('updated_at', __('base.updated_at'));
            $form->tools(function (Form\Tools $tools) {
                // 去掉跳转列表按钮
                $tools->disableListButton();
            });
        });
    }

/*
 * 删除接口中的数据
 */
    public function deleteApi($template_type, $template_no)
    {
        try {
            if ($template_type === 'area' && $template_no === '005') {
                // 删除区位模板信息
                $result = DB::connection('interface')->table('template_area_datas')->where(['template_type' => $template_type, 'template_no' => $template_no])->delete();
                DB::connection('interface')->table('template_area_images')->where(['template_type' => $template_type, 'template_no' => $template_no])->delete();
                if ($result) {
                    return DB::connection('interface')->table('template_subcolumn_vasseti_datas')->truncate();
                } else {
                    return false;
                }
            } else {
                /**
                 * 2017-11-21 18:37 add delete 下线发布删除缓存中的内容
                 */
                // $templateKey = 'template:area:';
                // $redis = Redis::connection('interface');
                // if ($redis->exists($templateKey . $template_no)) {
                //     // $redis->del($templateKey . $template_no);
                //     $redis->command('Del', [$templateKey . $template_no]);
                //     $redis->command('Del', [$templateKey . $template_no]);
                // }
                DB::connection('interface')->table('template_area_images')->where(['template_type' => $template_type, 'template_no' => $template_no])->delete();
                return DB::connection('interface')->table('template_area_datas')->where(['template_type' => $template_type, 'template_no' => $template_no])->delete();
            }
        } catch (\Exception $e) {
            dd($e->getMessage());
        }

    }
    /**
     * 获取区位图片信息
     */
    public static function getTemplateAreaImg($template_type, $template_no, $template_details_id)
    {
        // 获取全部的图片
        $imgs = [];
        // 获取图片区位信息
        $img              = [];
        $templateAreaImgs = DB::table('template_area_images')
            ->where(['template_type' => $template_type, 'template_no' => $template_no, 'template_details_id' => $template_details_id])
            ->whereNull('deleted_at')
            ->get();
        // return $templateAreaImgs;
        foreach ($templateAreaImgs as $key => $value) {
            $img['template_type'] = $value->template_type;
            $img['template_no']   = $value->template_no;
            $img['area_no']       = $value->area_no;
            $img['tag_no']        = $value->tag_no;
            $img['subcolumn_id']  = $value->subcolumn_id;
            $img['img']           = $value->img;
            $imgs[]               = $img;
        }
        return $imgs;
    }

    /**
     * 更新发布状态
     */
    public static function updatePublishStatus($content_template_id, $template_details_id)
    {
        try {

            // 更新已上线的发布状态为下线,已发布
            $contentTemplate = ContentTemplateDetails::onlineStatus()
                ->onlinePublished()
                ->where('id', '<>', $template_details_id)
                ->where('content_template_id', '=', $content_template_id)
                ->update(['online_status' => 0, 'publish_status' => 0, 'publish_down_status' => 1, 'offline_at' => date('Y-m-d H:i:s')]);

            DB::table('content_template_details')->where(['id' => $template_details_id])->update(['publish_status' => 1]);
        } catch (\Exception $e) {
            dd($e->getMessage());
        }
    }

    /**
     * 清空接口区位图片信息表
     */
    public static function deleteTemplateAreaImg($template_type, $template_no)
    {
        try {
            return DB::connection('interface')->table('template_area_images')->where(['template_type' => $template_type, 'template_no' => $template_no])->delete();
        } catch (\Exception $e) {
            dd($e->getMessage());
        }
    }
    /**
     * 删除模板数据
     */
    public static function deleteTemplateAreaData($template_type, $template_no)
    {
        try {
            return DB::connection('interface')->table('template_area_datas')->where(['template_type' => $template_type, 'template_no' => $template_no])->delete();
        } catch (\Exception $e) {
            dd($e->getMessage());
        }
    }
    /**
     * 区位模板数据
     */
    public function getTemplateAreaData($template_type, $template_no, $template_details_id)
    {
        // 每一条模板数据
        $data             = [];
        $datas            = [];
        $templateAreaData = TemplateAreaData::whereNotNull('template_details_id')->where(['template_details_id' => $template_details_id, 'template_type' => $template_type, 'template_no' => $template_no])->get();
        foreach ($templateAreaData as $key => $value) {
            // 模板类型
            $data['template_type'] = $value->template_type;
            // 模板编号, 例子:001
            $data['template_no'] = $value->template_no;
            // 资源类型, 1 => 直播, 2 => 专题，3 => 推荐位，4=>点播媒资 5=>栏目列表
            $data['resource_type'] = $value->resource_type;
            // 区位编号, 例如: AREA001x1x0y0
            $data['area_no'] = $value->area_no;
            // 具体到某一个位置的编号
            $data['tag_no'] = $value->tag_no;
            // 区位文件资源ID
            $data['resource_id'] = $value->resource_id;
            // 开始时间
            $data['start_time'] = $value->start_time;
            // 结束时间
            $data['end_time'] = $value->end_time;
            // 首页类型 1-首页 2-直播首页 3-点播首页 4回看首页
            $data['home_type'] = $value->home_type;
            // 栏目列表ID
            $data['collist_id'] = $value->collist_id;
            // 栏目ID
            $data['column_id'] = $value->column_id;
            // 二级栏目ID
            $data['subcolumn_id'] = $value->subcolumn_id;
            $datas[]              = $data;
        }
        return $datas;
    }

/**
 * 二级栏目媒资
 */
    public function getSubcolumnVassetiData($template_details_id)
    {
        // 每一条模板005的二级栏目
        $subcolumn = [];
        // 存放模板005的某一个二级栏目下的所有媒资
        $subcolumns = [];
        // 获取所有栏目数据
        $subColumnVatssetis = TemplateSubcolumnVassetiData::where(['template_details_id' => $template_details_id])->get();
        foreach ($subColumnVatssetis as $key => $value) {
            // 查询对应二级栏目下的媒资
            $subcolumn['subcolumn_id'] = $value->subcolumn_id;
            $subcolumn['area_no']      = $value->area_no;
            $subcolumn['vasseti_id']   = $value->vasseti_id;
            $subcolumn['type']         = $value->type;
            $subcolumns[]              = $subcolumn;
        }
        return $subcolumns;
    }

/**
 * 删除二级栏目媒资数据
 */
    public function deleteSubcolumnVassetiData()
    {
        try {
            return DB::connection('interface')->table('template_subcolumn_vasseti_datas')->delete();
        } catch (\Exception $e) {
            dd($e->getMessage());
        }
    }

    /**
     * 清除缓存
     */
    public function clearCache(Request $request)
    {
        // 判断此模板是否上线
        $contentTemplate = ContentTemplate::where(['id' => $request->content_template_id])->first();
        if (!empty($contentTemplate)) {
            $template_no = $contentTemplate->template_no;
            if ($template_no == '005') {
                $requestKey = 'template:area:5:*';
            } else {
                $templateKey = 'template:area:';
                $requestKey  = $templateKey . $template_no;
            }
            // 调用瀚动接口清除缓存的路由'
            $requestData = [
                'redis_key' => $requestKey,
            ];
            // 请求类型
            $type            = "post";
            $url             = config('custom.base.cache_host') . "clear_cache"; // http://10.69.42.146/
            $interfaceResult = proxy_http_request($type, $url, $requestData);
        }
        Flash::success('清除缓存成功!');
        return redirect(route('operation.content_template_details.index', ['content_template_id' => $request->content_template_id]));
    }
}
